# -*- coding:utf-8 -*-
from global_vars import g_logger
from functools import wraps
class command_base(object):
    _raw_string = ''
    _socket = None
    _command_id = 0
    _command_type = 0
    _command_status = 0
    _command_body = {}
    '''
    classdocs
    '''
    def __init__(self, obj_dec, socket):
        self._socket = socket
        import common_strings
        _command_id = obj_dec[common_strings.COMMAND_ID]
        _command_body = obj_dec[common_strings.COMMAND_BODY]
    def execute(self):
        ''' must implement by subclasses, use this method like interfaces
        '''
    def sendResponse(self, response):
        ''' send response to clients
            response: must subclass of response_base
        '''
        if not (response is response_base):
            raise 'sendResponse: response is not a response_base'
        fl = self._socket.makefile()
        resp_str = response.to_string()
        g_logger.debug('send response:' % resp_str)
        fl.write(resp_str)
        fl.flush()

class response_base(object):
    _command_id = 0
    _command_status = 0
    _command_body = {}
    '''
    classdocs
    '''
    def __init__(self):
        pass
    def add_to_body(self, key, value):
        self._command_body[key] = value
    def _get_obj(self):
        from common import common_strings
        obj_whole = {}
        obj_whole[common_strings.COMMAND_ID] = self._command_id
        obj_whole[common_strings.COMMAND_STATUS] = self._command_status
        obj_whole[common_strings.COMMAND_BODY] = self._command_body
        return obj_whole
    def raw_string(self):
        from common.cipher import cipherhelper
        return cipherhelper.do_json_dump(self._get_obj())
    def to_string(self):
        from common.cipher import cipherhelper
        return cipherhelper.encode(self._get_obj())

class error_response(response_base):
    def __init__(self, err_cmd_id, err_str=None):
        import command_ids, common_strings
        self._command_id = command_ids.Invalid
        self.add_to_body(common_strings.ERR_COMMAND_ID, err_cmd_id)
        if err_str: self.add_to_body(common_strings.ERR_COMMAND_DESC, err_str)

class result_object(object):
    result = True
    errcode = 0
    errstr = ''
    innerobj = None

def check_login(func):
    @wraps(func)
    def new_func(*args, **kwargs):
        return func(*args, **kwargs)
    return new_func

